package com.daocao.hua.api.requestInfo;

import android.animation.Animator;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.LinearLayout;

import com.daocao.hua.R;
import com.daocao.hua.activity.CameraActivity;
import com.daocao.hua.activity.Idcardv2Activity;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.ChsiBean;
import com.daocao.hua.api.bean.ChsiLoginBean;
import com.daocao.hua.api.bean.IdCardIndentityBean;
import com.daocao.hua.api.bean.LoginBean;
import com.daocao.hua.api.bean.RelativeAddressBean;
import com.daocao.hua.api.bean.UpdateAddressBean;
import com.daocao.hua.api.bean.UploadSubmitIdcardBean;
import com.daocao.hua.api.callback.IdcardV2Contract;
import com.daocao.hua.api.callback.LoginContract;
import com.daocao.hua.model.IdentityModel;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.view.CanShadowDrawable;
import com.daocao.hua.view.animation.Techniques;
import com.daocao.hua.view.animation.YoYo;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/5/14.
 */

public class IdcardV2Request extends BaseRequest<IdcardV2Contract.View> implements IdcardV2Contract.Presenter<IdcardV2Contract.View> {

    public static IdcardV2Request create() {
        return new IdcardV2Request();
    }


    public void startCameraActivity() {
        Intent localIntent = new Intent(BaseContext, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", "idcard.jpg");
        localIntent.putExtra("type", "idcard");
        ((Idcardv2Activity) BaseContext).startActivityForResult(localIntent, 100);
    }

    float dp2Px(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, BaseContext.getResources().getDisplayMetrics());
    }

    //    设置阴影
    public void setGradientTotal(View layout) {
        CanShadowDrawable.Builder.on(layout)
                .radius(dp2Px(6))
                .shadowColor(Color.parseColor("#FEAB67"))
//                .shadowDx(1)
//                .bgColor(Color.WHITE)
                .shadowDy(dp2Px(1))
                .shadowRange(dp2Px(6))
                .offsetTop(dp2Px(6))
                .offsetBottom(dp2Px(6))
                .offsetLeft(dp2Px(6))
                .offsetRight(dp2Px(6))
                .create();
    }


    public void setGradientGreyTotal(boolean hasUp, View layout) {
        float up = 0;
        if (hasUp) {
            up = dp2Px(6);
        } else {
            up = dp2Px(0);
        }
        CanShadowDrawable.Builder.on(layout)
                .radius(dp2Px(6))
                .shadowColor(Color.parseColor("#999999"))
//                .shadowDx(1)
                .shadowDy(dp2Px(1))
                .shadowRange(dp2Px(6))
                .offsetTop(up)
                .offsetBottom(dp2Px(6))
                .offsetLeft(dp2Px(6))
                .offsetRight(dp2Px(6))
                .create();
    }


    //    从上往下变大拉伸
    public void setAnimation(boolean isBank, View target) {
        YoYo.with(Techniques.values()[2])
                .duration(1200)
                .pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
                .interpolate(new AccelerateDecelerateInterpolator())
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        if (isBank) {
                            setGradientGreyTotal(false, target);
                        }
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {

                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                })
                .playOn(target);
    }


    //    缩小往左
    public void setAnimationOne(View target) {
        YoYo.with(Techniques.values()[0])
                .duration(1200)
//                .repeat(YoYo.INFINITE)
                .pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
                .interpolate(new AccelerateDecelerateInterpolator())
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mView.animationOneEnd();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                })
                .playOn(target);
    }

    //    从右往左
    public void setAnimationTwo(View target) {
        YoYo.with(Techniques.values()[1])
                .duration(1200)
//                .repeat(YoYo.INFINITE)
                .delay(500)
                .pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
                .interpolate(new AccelerateDecelerateInterpolator())
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                })
                .playOn(target);
    }

    public void setAnimationBank(View target) {
        YoYo.with(Techniques.values()[3])
                .duration(600)
//                .repeat(YoYo.INFINITE)
                .pivot(YoYo.CENTER_PIVOT, YoYo.CENTER_PIVOT)
                .interpolate(new AccelerateDecelerateInterpolator())
                .withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        target.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                })
                .playOn(target);
    }

    public CityPicker getCityPicker() {
        return new CityPicker.Builder(BaseContext)
                .textSize(12)
                .title("请选择地区选择")
                .backgroundPop(0xa0000000)
                .titleBackgroundColor("#ffffff")
                .titleTextColor("#000000")
                .confirTextColor("#03a9f4")    //蓝色
                .cancelTextColor("#03a9f4")    //蓝色
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
    }


    @Override
    public void getIdentityInfo(int paramInt, String paramString) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        IdCardIndentityBean bean = new IdCardIndentityBean();
        bean.img = paramString;
        Api.api_service.getIdentityInfo(paramInt, bean).compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() != 0) {
                        mView.getIdentityInfoSuccess(paramInt, result);
                    }
                });
    }

    @Override
    public void getSubmitidCard(UploadSubmitIdcardBean item) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        Api.api_service.getSubmitidCard(item).compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getSubmitidCardSuccess(result);
                });
    }

    @Override
    public void getChsiCode(String username, String password) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        ChsiBean bean = new ChsiBean();
        bean.username = username;
        bean.password = password;
        Api.api_service.getChsiCodeInfo(bean).compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getChsiCodeSuccess(result);
                });
    }

    @Override
    public void getChsiLogin(String username, String password, String captcha) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        ChsiLoginBean bean = new ChsiLoginBean();
        bean.username = username;
        bean.password = password;
        if (!TextUtils.isEmpty(captcha)) {
            bean.captcha = captcha;
        }
//
        Api.api_service.getChsiLoginInfo(bean).compose(RxLifeUtil.NocheckOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    if (result.getStatus() == 1) {
                        mView.getChsiLoginSuccess(result);
                    } else if (result.getStatus() == 2) {
                        mView.getChsiNeedCode(result.captchaImage);
                    } else {
                        mView.getChsiLoginFail(result);
                    }
                });
    }


    @Override
    public void getBankList() {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        Api.api_service.getBankList().compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getBankListSuccess(result);
                });
    }

    @Override
    public void getRelativeAddress(String address, String name, String mobile, String relationship) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
//        mView.onRequestStart();
        RelativeAddressBean bean = new RelativeAddressBean();
        bean.contacts = new ArrayList<>();
        RelativeAddressBean.ContactsBean item = new RelativeAddressBean.ContactsBean();
        item.address = address;
        item.name = name;
        item.mobile = mobile;
        item.relationship = relationship;
        bean.contacts.add(item);
        Api.api_service.getRelativeAddress(bean).compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getRelativeAddressSuccess();
                });
    }

    @Override
    public void updateAddress(String name, String address, String phone, String province, String city, String area) {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        UpdateAddressBean bean = new UpdateAddressBean();
        bean.address = address;
        bean.name = name;
        bean.phone = phone;
//        bean.provinces_cities = provinces_cities;
        bean.province = province;
        bean.city = city;
        bean.area = area;
        Api.api_service.updateAddress(bean).compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.updateAddressSuccess(result);
                });
    }

    @Override
    public void getQuota() {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
        mView.onRequestStart();
        Api.api_service.getQuota().compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getQuotaSuccess(result.text);
                });
    }

    @Override
    public void getRelativeList() {
        if (!Network.checkNetwork(BaseContext)) {
            ToastUtil.makeText(BaseContext, networkFail).show();
            return;
        }
//        mView.onRequestStart();
        Api.api_service.getRelativeList().compose(RxLifeUtil.checkOn(BaseContext)).
                doFinally(() -> {
                    try {
                        mView.complete();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    mView.getRelativeListSuccess(result);
                });
    }

    public String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = BaseContext.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
//            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }
}
